
const storage = chrome.storage;
// 监听浏览器标签页的创建和关闭事件
chrome.tabs.onCreated.addListener(updateTabList);
chrome.tabs.onRemoved.addListener(updateTabList);
chrome.tabs.onActivated.addListener(updateTabList);
chrome.tabs.onReplaced.addListener(updateTabList);
chrome.tabs.onUpdated.addListener(updateTabList);
function updateTabList() {
  chrome.tabs.query({ currentWindow: true }, function (tabs) {
    // for (let i = 0; i < tabs.length; i++) {
    //   if (tabs[i].active) {
    //     let tableid = tabs[i].id
    //     chrome.tabs.get(tableid, function (tab) {
    //       // 获取当前活动标签页的详细信息
    //       let str = 'ruten.com.tw/'
    //       let url = tab.url == '' ? tab.pendingUrl : tab.url
    //       if (url.includes(str)) {
    //         chrome.action.setPopup({ popup: './popup.html' });
    //       } else {
    //         chrome.action.setPopup({ popup: './popup.html' });
    //       }
    //     });
    //   }

    // }
  })

}

let ws = null;
let heartbeatInterval = null;
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;
const reconnectDelay = 3000; // 重连间隔（毫秒）
const heartbeatTime = 10000; // 心跳间隔（毫秒）

let isfirst = 0
let ENVIRONMENT_PRINT_ID
let browserParams = {}
let isfirestPlug = 0

// 初始化WebSocket连接
function initWebSocket() {
  ws = new WebSocket(`ws://localhost:${10000 + ENVIRONMENT_PRINT_ID}`);

  // 连接成功
  ws.onopen = () => {
    reconnectAttempts = 0; // 重置重连计数器
    startHeartbeat(); // 启动心跳
    sendToElectron({ type: 'one_status', payload: 'ready' }); // 发送就绪通知
  };

  // 接收消息
  ws.onmessage = (event) => {
    let data = JSON.parse(event.data)
    console.log(data);

    if (data.type == 'electron_one_status') {
      browserParams = data.browserParams
      getRealIPLocation();
    }
  };

  // 连接关闭
  ws.onclose = (event) => {
    console.log('连接关闭，代码:', event.code);
    stopHeartbeat();
    if (reconnectAttempts < maxReconnectAttempts) {
      setTimeout(initWebSocket, reconnectDelay); // 自动重连
      reconnectAttempts++;
    }
  };

  // 连接错误
  ws.onerror = (error) => {
    console.error('WebSocket错误:', error);
    ws.close(); // 触发onclose
  };
}

// 启动心跳检测
function startHeartbeat() {
  heartbeatInterval = setInterval(() => {
    if (ws?.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({ type: 'ping' })); // 发送心跳
    }
  }, heartbeatTime);
}

// 停止心跳
function stopHeartbeat() {
  if (heartbeatInterval) {
    clearInterval(heartbeatInterval);
    heartbeatInterval = null;
  }
}

// 发送消息到Electron
function sendToElectron(data) {
  if (ws?.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify(data));
  } else {
    console.error('消息发送失败：连接未就绪');
  }
}


function getRealIPLocation() {
  fetch("http://ip-api.com/json")
    .then(response => response.json())
    .then(data => {
      if (data.status === "success") {
        browserParams.activeIp = data
        chrome.runtime.sendMessage({ type: "updateBrowser", data: browserParams });
      }
    });
}


if (isfirestPlug == 0) {
  setTimeout(() => {
    isfirestPlug = 1
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      const currentTabId = tabs[0].id;
      const popupUrl = chrome.runtime.getURL('popup.html'); // 获取插件的 popup 页面 URL

      // 更新当前标签页的 URL，将其切换为插件的 popup 页面
      chrome.tabs.update(currentTabId, { url: popupUrl });
    });
  }, 1000);
}





chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.action === 'web_first') {
    sendResponse({
      message: "success"
    });

    if (isfirst == 0 && request.ENVIRONMENT_PRINT_ID != undefined && request.ENVIRONMENT_PRINT_ID != null) {
      isfirst = 1
      ENVIRONMENT_PRINT_ID = request.ENVIRONMENT_PRINT_ID
      initWebSocket()
    }
  } else if (request.action === 'refresh_ip') {
    sendResponse({
      message: "success"
    });
    getRealIPLocation()
  }

});





// 保存数据到chrome.storage
function saveData(data, key) {
  const obj = {};
  obj[key] = data;
  storage.local.set(obj, function () {
    // //console.log('Data saved successfully.');
  });
}


// // 读取chrome.storage中的数据
// function loadData(key, callback) {
//   chrome.storage.local.get([key], function (result) {
//     const data = result[key];
//     callback(data);
//   });
// }



// function sendMessageToTab(message) {
//   loadData('relationtabsid', function (tabsid) {
//     // console.log(tabsid);
//     chrome.tabs.sendMessage(tabsid, message);
//   })

// }


